<template>
  <view class="nickname-page">
    <!-- 昵称输入区域 -->
    <view class="input-container">
      <input 
        class="nickname-input" 
        v-model="nickname" 
        placeholder="请输入昵称" 
        :maxlength="20"
        focus
      />
      <view class="char-count">{{ nickname.length }}/20</view>
    </view>
    
    <!-- 提示信息 -->
    <view class="tips">
      <text class="tip-text">支持中英文、数字,长度2-20个字符</text>
    </view>
    
    <!-- 保存按钮 -->
    <view class="save-btn-container">
      <button 
        class="save-btn" 
        :class="{ 'save-btn-active': nickname.length > 2 }"
        :disabled="nickname.length < 2"
        @click="saveNickname"
      >
        保存
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { updateUserProfile } from '@/api/auth';

const userStore = useUserStore();

// 获取当前昵称
const nickname = ref('');

// 页面加载时获取当前用户昵称
onMounted(() => {
  nickname.value = userStore.userInfo?.nickname || '';
});

// 保存昵称
const saveNickname = async () => {
  const trimmedNickname = nickname.value.trim();
  
  if (trimmedNickname.length < 2) {
    uni.showToast({
      title: '昵称长度至少2个字符',
      icon: 'none'
    });
    return;
  }

  if (trimmedNickname.length > 20) {
    uni.showToast({
      title: '昵称长度不能超过20个字符',
      icon: 'none'
    });
    return;
  }
  
  try {
    uni.showLoading({ title: '保存中...' });
    
    // 调用后端接口更新昵称
    if (userStore.userInfo) {
      await updateUserProfile(userStore.userInfo.customerId, {
        nickname: trimmedNickname
      });
      
      // 更新 Store 中的用户信息
      userStore.setUserInfo({
        ...userStore.userInfo,
        nickname: trimmedNickname
      });
      
      uni.hideLoading();
      
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      });
      
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    }
  } catch (error) {
    console.error('保存昵称失败:', error);
    uni.showToast({
      title: '保存失败,请重试',
      icon: 'none'
    });
  }
};
</script>

<style scoped>
.nickname-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
}

.input-container {
  background-color: #ffffff;
  border-radius: 10rpx;
  padding: 30rpx;
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.nickname-input {
  flex: 1;
  font-size: 32rpx;
  color: #333333;
  padding: 10rpx 0;
}

.char-count {
  font-size: 28rpx;
  color: #999999;
  margin-left: 20rpx;
}

.tips {
  padding: 0 20rpx;
  margin-bottom: 40rpx;
}

.tip-text {
  font-size: 24rpx;
  color: #999999;
}

.save-btn-container {
  padding: 0 20rpx;
}

.save-btn {
  width: 100%;
  height: 80rpx;
  background-color: #cccccc;
  border-radius: 10rpx;
  font-size: 32rpx;
  color: #ffffff;
  border: none;
}

.save-btn-active {
  background-color: #00C853;
}

.save-btn:disabled {
  background-color: #cccccc;
  color: #ffffff;
}
</style>